import 'package:flutter/cupertino.dart';

import 'package:flutter_widgets_pc/widgets/sectionListView/indexer/indexer.dart';
import 'package:flutter_widgets_pc/widgets/sectionListView/indexer/indexer_util.dart';

import '../../resources/kq_theme_colors.dart';
import 'kq_section_view.dart';

///基于KqSectionListView，主要是快速实现索引和分区
class KqSectionIndexView<T extends Indexer> extends StatefulWidget {
  ///cell的对应UI
  final Widget Function(int section, int row, T object) itemBuilder;

  /// 数据，需要继承[Indexer],需要实现[getFullName]方法，返回需要排序索引的字段
  final List<T> data;

  /// 设置索引为大写或者小写，默认小写
  final LatterType type;

  /// 是否需要数字索引，默认不需要，不需要如果遇到数字会排在最后面的[#]分类
  final bool isIndexNumber;

  const KqSectionIndexView({
    super.key,
    required this.data,
    required this.itemBuilder,
    this.type = LatterType.lowerCase,
    this.isIndexNumber = false,
  });

  @override
  State<StatefulWidget> createState() => _KqSectionIndexViewState();
}

class _KqSectionIndexViewState<T extends Indexer>
    extends State<KqSectionIndexView<T>> {
  Map<String, List<T>> sectionData = {};
  List<String> indexData = [];

  @override
  void initState() {
    super.initState();
    sectionData = IndexerUtil.getSectionData(
        data: widget.data,
        type: widget.type,
        isIndexNumber: widget.isIndexNumber);
    indexData = IndexerUtil.getIndexData(
        data: widget.data,
        type: widget.type,
        isIndexNumber: widget.isIndexNumber);
  }

  @override
  Widget build(BuildContext context) {
    return KqSectionListView<T>(
      section: sectionData.length,
      sectionHeight: 30,
      isShowIndex: true,
      isSameHeight: true,
      isFixtop: true,
      indexList: indexData,
      indexTextColor: KqThemeColors.textBlue,
      indexFont: 10,
      headerBuilder: ((section) {
        return Container(
          height: 30,
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.only(left: 16),
          color: KqThemeColors.bgF4,
          child: Text(indexData[section],
              style: TextStyle(fontSize: 14, color: KqThemeColors.text333)),
        );
      }),
      rowHeight: (section) {
        return 56;
      },
      itemList: ((section) {
        List<T>? model = sectionData[indexData[section]];
        return model ?? [];
      }),
      itemBuilder: widget.itemBuilder,
    );
  }
}
